# -*- coding:utf-8 -*-
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask import flash
from flask import session
from flask import g
from flask_login import current_user

from app import db
from app.views.personal_center import personal_center
from app.models.account import Staff, DefPassword
from app.models.log import StaffLog
from app.models.message import MessageMiddle, Message

from app.tools.permission import permission
from app.tools.log import log
from app.tools.redis_op import Operator


op = Operator()

def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


personal_center.before_request(signin_required)

def mark_read(type):  # 把消息标记为已读
    models = Message.query.filter_by(type=message_dict[type]).all()
    for m in models:
        messages = MessageMiddle.query.filter_by(status=False, message_id=m.id).all()
        for msg in messages:
            msg.read()
            msg.save()



@personal_center.before_request
@permission(['service', 'director', 'manage', 'finance', 'review', 'admin', 'super'])
def check_permission():
    g.kw = {}
    role = session.get('role')
    if role == 'service':
        g.kw['server_id'] = session.get('sid')
    else:
        g.kw['role'] = role
    return
def update_xfrs():
    import uuid
    xfrs = str(uuid.uuid4())
    op.hset('xfrs', xfrs, 0)
    return xfrs


roles = {u'客服部': 'service', u'综合管理部': 'manage', u'车辆审批部': 'review',
         u'财务部': 'finance', u'人资行政部': 'hr', u'管理层': 'admin',
         u'客服主管': 'director', u'业务上传': 'upload', u'网站设置': 'setup',
         u'超级管理员': 'super'}

roles_reverse = {v: k for k, v in roles.items()}
dep = ['manage', 'review', 'finance', 'admin', 'director', 'super']
ser = ['service', 'admin', 'director', 'super']


@personal_center.route('/', methods=['GET'])
@personal_center.route('/message/loan', methods=['GET'])
def loan():  # 类型是 贷款 的所有消息
    if session['role'] in ser:
        pass
    else:
        return redirect(url_for('.review'))
    mark_read('loan')
    ms = Message.query.filter_by(type=u'贷款').order_by(Message.timestamp.desc()).all()
    print ms
    return render_template('personal_center/loan.html',
                           ms=ms)


@personal_center.route('/message/review', methods=['GET'])
def review():  # 类型是 审核 的所有消息
    mark_read('review')
    rs = Message.query.filter_by(type=u'审核').order_by(Message.timestamp.desc()).all()

    return render_template('personal_center/review.html',
                           rs=rs)


@personal_center.route('/message/distribute', methods=['GET'])
def distribute():  # 类型是 分单 的所有消息
    mark_read('distribute')
    rs = Message.query.filter_by(type=u'分单').order_by(Message.timestamp.desc()).all()

    return render_template('personal_center/distribute.html',
                           rs=rs)


@personal_center.route('/edit_password', methods=['GET'])  # 修改密码页面
def edit_password():
    xfrs = update_xfrs()
    return render_template('personal_center/edit_password.html',
                           xfrs=xfrs)


@personal_center.route('/update_password', methods=['POST'])
def update_password():
    form = request.form
    xfrs = form.get('xfrs')
    old_password = form.get('old_password')
    new_password = form.get('new_password')

    if xfrs in op.r.hkeys('xfrs') and old_password and new_password:
        op.r.hdel('xfrs', xfrs)
        if current_user.verify_password(old_password):
            current_user.password = new_password
            db.session.add(current_user)
            db.session.commit()
            flash(u'修改密码成功')
            log(u'修改密码')
            return redirect(url_for('.edit_password'))
        else:
            flash(u'密码错误，请重新输入')
            return redirect(url_for('.edit_password'))
    else:
        flash(u'你还没有输入密码')
        return redirect(url_for('.edit_password'))


message_dict = {
    'loan': u'贷款',
    'review': u'审核',
    'distribute': u'分单'
}


@personal_center.route('/check_message/all', methods=['POST'])
def check_message():  # 如果有未读消息 界面右上角的管理员显示红点
    dep.extend(ser)
    if session['role'] in dep:  # 因为是在基模板 需要判断角色
        ms = MessageMiddle.query.filter_by(status=False, **g.kw).all()
    else:
        return jsonify(dict(
            message_not_read=False,
            success=True
        ))
    if len(ms) > 0:
        return jsonify(dict(
            success=True,
            message_not_read=True,
            type=None
        ))
    else:
        return jsonify(dict(
            success=True,
            message_not_read=False,
            type=None
        ))


@personal_center.route('/check_message/', methods=['POST'])
def check_message_type():  # 如果有未读消息 个人中心 按类型显示红点
    query = MessageMiddle.query.filter_by(status=False, **g.kw)
    loans = query.filter_by(type=u'贷款').all()
    reviews = query.filter_by(type=u'审核').all()
    distribute = query.filter_by(type=u'分单').all()

    if len(loans) > 0 and len(reviews) > 0 and len(distribute) > 0:
        return jsonify(dict(
            success=True,
            message_not_read=True,
            type='all'
        ))
    elif len(loans) > 0:
        return jsonify(dict(
            success=True,
            message_not_read=True,
            type='loan'
        ))
    elif len(reviews) > 0:
        return jsonify(dict(
            success=True,
            message_not_read=True,
            type='review'
        ))
    elif len(distribute) > 0:
        return jsonify(dict(
            success=True,
            message_not_read=True,
            type='distribute'
        ))
    else:
        return jsonify(dict(
            success=True,
            message_not_read=False,
            type=None
        ))
